<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminMenu;
use Illuminate\Http\Request;
use App\Services\BaseService;
use App\Models\AdminRole;
use Illuminate\Support\Facades\DB;
use App\Models\AdminRoleMenu;
use Illuminate\Database\Eloquent\Relations\HasMany;

class RoleController extends Controller
{

    //
    public function index()
    {
        $roles = AdminRole::query()
                          ->get();

        return $roles;
    }

    public function create(Request $request)
    {
        $id = $request->query('id', 0);

        $body = $request->post();

        DB::beginTransaction();
        try {
            $role = AdminRole::query()
                             ->findOrNew($id);

            $role->name = $body['name'];

            $role->save();

            AdminRoleMenu::query()
                         ->where('role_id', $role->id)
                         ->whereNotIn('menu_id', $body['menus'])
                         ->delete();

            foreach ($body['menus'] as $menu) {
                AdminRoleMenu::query()
                             ->firstOrCreate(['role_id' => $role->id, 'menu_id' => $menu]);
            }

            DB::commit();

            return $role;
        } catch (\Exception $e) {
            abort(500, $e->getMessage());
            DB::rollBack();
        }
    }

    public function menu(BaseService $baseService)
    {
        $menu = AdminMenu::query()
                         ->selectRaw('id,id as `key`,parent_id,title')
                         ->orderBy('order')
                         ->get();

        return $baseService->getTree($menu->toArray(), 0, 'key');
    }

    public function show(int $id)
    {
        $adminRole = AdminRole::query()
                              ->find($id);

        $menuIds = AdminRoleMenu::query()
                                ->where('role_id', $id)
                                ->pluck('menu_id');

        $adminRole->menu = $menuIds;

        return $adminRole;
    }
}
